<?php
/**
 * User.php
 *
 * 用户数据对象模型类.
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://momoger.com/license
 *
 * @category	Momoger
 * @package 	Momoger_Model
 * @author 		Leo
 * @version    	1.0
 * @copyright  	Copyright © 2009 www.momoger.com All Rights Reserved.
 * @license    	http://momoger.com/license     New BSD License
 */

/** Momoger_Model_Abstract */
//require_once 'Abstract.php';

/**
 * 用户数据对象模型类, 该类提供用户登录， 注册， 提取修改个人资料， 个人相册， 个人相册分类信息等接口.
 *
 * @category 	Momoger
 * @package		Momoger_Model
 * @copyright  	Copyright © 2009 www.momoger.com All Rights Reserved.
 * @license    	http://momoger.com/license     New BSD License
 */
class Momoger_Model_User extends Momoger_Model_Abstract {

	/**
	 * 错误异常信息
	 *
	 * @var array
	 */
	private $error = array();

	/**
	 * 系统状态信息模型
	 *
	 * @var Momoger_Model_Profile
	 */
	private $_profile = null;

	/**
	 * 用户相册分类模型
	 *
	 * @var Momoger_Model_Category
	 */
	private $_category = null;

	/**
	 * 用户图片模型
	 *
	 * @var Momoger_Model_Photo
	 */
	private $_photo = null;

	/**
	 * 用户归档信息模型
	 *
	 * @var Momoger_Model_Archive
	 */
	private $_archive = null;

	/**
	 * 构造函数.
	 *
	 * @param mixed $options 快速设置参数.
	 */
	public function __construct($options = null) {
        parent::__construct($options);
	}

    /**
     * 检查用户帐号是否存在, 存在返回 true， 否则返回 false
     *
     * @param string $account 用户帐号
     * @return boolean
     */
    public function accountIsExists($account = null) {
    	if (!$account) {
    		return FALSE;
    	}
    	$_id = $this->get('userID');
    	$this->remove('userID');
    	$this->findRow("userName = '$account'");
    	if ($this->get('userID')) {
    		if ($_id) {
    			$this->set('userID', $_id);
    		}
    		return TRUE;
    	}
    	return FALSE;
    }

    /**
     * 获取指定用户信息
     *
     * @param int $user_id 用户ID
     * @return array
     */
    public function getUser($user_id) {
    	return $this->find($user_id)->getAll();
    }

    /**
     * 用户登录系统
     *
     * @param array $identities 用户登录信息
     * @return boolean
     */
    public function userLogin(array $identities) {
    	if (!count($identities)) {
    		$this->error = array('msg' => 'Login false! I have give your identity information nothing!', 'back' => '/login');
    		return FALSE;
    	}

    	//get the default db adapter
		$dbAdapter = Zend_Registry::get('defaultDbAdapter');

		//use db valid user identity
		$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

		//set validate condition and data
		$authAdapter->setTableName('users');
		$authAdapter->setIdentityColumn('userName');
		$authAdapter->setCredentialColumn('userPasswd');
		$authAdapter->setIdentity($identities['account']);
		$authAdapter->setCredential($identities['passwd']);
		$authAdapter->setCredentialTreatment('MD5(?)');

		//use zend auth validate user
		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($authAdapter);

    	//user post login data is valid or not
		if (!$result->isValid()) {
			$this->error = array('msg' => 'Sorry! you can not login system! data invalid!', 'back' => '/login');
    		return FALSE;
		}

		//use account is been closed or not
		$data = $authAdapter->getResultRowObject(null, null);
		//Zend_Debug::dump($data);

		//use account is valid or not
    	if (!(int)$data->userValid) {
			$this->error = array('msg' => 'Sorry! your account is closed now!', 'back' => '/');
    		return FALSE;
		} else {

			//modify use log data
			$data->userLogs += 1;
			$data->userLogAt = time();
			$this->set(get_object_vars($data))->save();

			//save data to session
			$auth->getStorage()->write($data);

			return TRUE;
		}
    }

    /**
     * 用户登出系统
     *
     * @return void
     */
    public function userLogout() {
    	//注销身份信息
    	Zend_Auth::getInstance()->clearIdentity();
    }

    /**
     * 保存用户注册数据
     *
     * @param array $data 注册提交数据
     * @return Momoger_Model_User | false
     */
    public function saveUserRegist(array $data) {
    	//save user data
		$this->set(array(
			'userName' => $data['account'],
			'userPasswd' => md5($data['passwd']),
			'userNick' => $data['account'],
			'userEmail' => $data['email'],
			'userValid' => 'development' == APPLICATION_ENV ? 1:0,
			'userLogs' => 1,
			'userLogAt' => time(),
			'userRegAt' => time()
		))->save();

		$userID = $this->get('userID');
		if ($userID) {
			//add user default photo category
			$this->category()->set(array('userID' => $userID, 'categoryType' => 'article', 'categoryDeleted' => 0, 'categoryName' => 'Default'))->save();

			//add user default article category
			$this->category()->reset()->set(array('userID' => $userID, 'categoryType' => 'photo', 'categoryDeleted' => 0, 'categoryName' => 'Default'))->save();

			//add system user regiest number
			$this->profile()->getProfile(Momoger_Model_Profile::REGIST_USER_NUMBER);
			$this->profile()->set('pValue', ((int)$this->profile()->get('pValue') + 1))->save();

			return $this;
		}

		return FALSE;
    }

    /**
     * 获取异常信息
     *
     * @return array
     */
    public function getErrorMsg() {
    	return $this->error;
    }

    /**
     * 修改用户添加图片或者日志成功后系统统计信息. 日志系统系统信息修改不在此处. 单独修改.
     *
     * @param int $user_id 用户ID
     * @param int $category_id 分类ID
     * @param string $type 类型
     * @return boolean
     */
    public function addNewSuccess($user_id, $category_id, $type = 'photo') {
		if (!$user_id || !$category_id || !in_array($type, array('article', 'photo'))) {
			return false;
		}

		$this->category()->find($category_id)->set('categoryCounts', $this->category()->get('categoryCounts') + 1)->save();

		$_archive = $this->archive()->getNowArchive($user_id, $type);
		$this->archive()->set('archiveCounts', $_archive['archiveCounts'] + 1)->save();

		if ('photo' == $type) {
			$this->find($user_id)->set('userPhotos', $this->get('userPhotos') + 1)->save();
			$this->profile()->find(Momoger_Model_Profile::TOTAL_PHOTO_NUMBER)->set('pValue', $this->profile()->get('pValue') + 1)->save();
		}

    	if ('article' == $type) {
			$this->find($user_id)->set('userArticles', $this->get('userArticles') + 1)->save();
			$this->profile()->find(Momoger_Model_Profile::TOTAL_ARTICLE_NUMBER)->set('pValue', $this->profile()->get('pValue') + 1)->save();
		}

		return TRUE;
    }

    /**
     * 获取信息分类模型
     *
     * @return Momoger_Model_Category
     */
    protected function category() {
    	if (null === $this->_category) {
    		$this->_category = new Momoger_Model_Category();
    	}
    	return $this->_category;
    }

    /**
     * 获取系统状态模型
     *
     * @return Momoger_Model_Profile
     */
    protected function profile() {
    	if (null === $this->_profile) {
    		$this->_profile = new Momoger_Model_Profile();
    	}
    	return $this->_profile;
    }

    /**
     * 获取图片模型
     *
     * @return Momoger_Model_Photo
     */
    protected function photo() {
    	if (null === $this->_photo) {
    		$this->_photo = new Momoger_Model_Photo();
    	}
    	return $this->_photo;
    }

    /**
     * 获取归档信息模型
     *
     * @return Momoger_Model_Archive
     */
    protected function archive() {
    	if (null === $this->_archive) {
    		$this->_archive = new Momoger_Model_Archive();
    	}
    	return $this->_archive;
    }

    /**
     * 获取数据地图对象.
     *
     * @return Momoger_Model_Mapper_User
     */
    protected function getMapper() {
        if (null === $this->_mapper) {
            $this->setMapper(new Momoger_Model_Mapper_User());
        }
        return $this->_mapper;
    }
}